﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace QQCommClient
{
    public partial class Form1 : Form
    {
        private TcpClient client;
        private Thread t;
        private Socket sock;
        private bool close = false;

        public Form1()
        {
            InitializeComponent();
        }

        // 连接 
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (client == null)
                client = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(txtLoalPort.Text)));

            if (t == null)
                t = new Thread(new ThreadStart(ReciverMessage));
            t.IsBackground = true;
            t.Start();
            btnSend.Enabled = true;
            btnConnect.Enabled = false;
        }

        // 接收消息 
        private void ReciverMessage()
        {
            client.Connect(IPAddress.Parse(txtSerIP.Text), int.Parse(txtSerPort.Text));
            while (true)
            {
                if (close)
                    break;
                //NetworkStream nws = client.GetStream(); 
                //StreamReader sr = new StreamReader(nws); 
                //string message = sr.ReadToEnd(); 
                //sr.Close(); 
                if (sock == null)
                    sock = client.Client;
                byte[] buff = new byte[100];
                sock.Receive(buff);
                string message = Encoding.Default.GetString(buff);
                this.lstMessage.Items.Add(message);
            }
            Thread.CurrentThread.Abort();
        }

        // 发送消息 
        private void btnSend_Click(object sender, EventArgs e)
        {
            string message = this.txtInput.Text;
            byte[] buff = Encoding.Default.GetBytes(message);
            sock.Send(buff);
            txtInput.Text = "";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            close = true;
            sock.Close();
        }




    }

}
